Ext.namespace('Ext.plot');

Ext.plot.panel = Ext.extend(Ext.Panel, {
    helpText:{groupByTip: 'Type the names of the columns by which to group the data on the X axis for plotting.'},
    initComponent: function() {
            xaxis_select = [];
            for (i = 0; i < config[current_genome].samples.columns.length; i++) {
                //Ext.getCmp('plotSampleSelect').getValue()
                    xaxis_select.push([config[current_genome].samples.columns[i]['dataIndex'],
                    config[current_genome].samples.columns[i]['header']])					
            }
                        
            Ext.apply(this, {
                    split: true,
                    margins: '0 0 0 0',
                    title: 'Plot',
                    id: 'plotPanel',
                    layout: 'border',
                    autoScroll: true,
                    items: [{
                        xtype: 'form',
                        region:'south',
                        id:'plotControls',
                        frame:true,
                        layout:'Hbox',
                        layoutConfig: {
                            align:'middle',
                            pack:'center',
                            padding:5
                        },
                        items: [
                        {
                            xtype:'tbtext',
                            text:'Group By'+ '<img src="images/Information.png" class="tip" id="plot_group_by"/>:'
                        },
                        {										
                            xtype: 'superboxselect',
                            //fieldLabel: 'Group By',
                            emptyText: 'Select attributes to group by on X axis.',
                            id: 'plotSampleSelect',
                            allowBlank:false,
                            mode:'local',
                            width:300,
                            store:xaxis_select
                        }, {
                            xtype:'button',
                            name:'updateplot',
                            text:'Update',
                            handler:function() {this.display()},
                            scope:this
                        },
                        {xtype:'spacer',width:50,flex:1},
                        {
                            xtype:'radiogroup',
                                id: 'graphType',
                                width:200,
                                
                                items: [
                                {
                                        id: "bar",
                                        name: 'graph',
                                        boxLabel: "Bar Graph",
                                        scope:this
                                },{
                                        id: "line",
                                        name: 'graph',
                                        boxLabel: "Line Graph",
                                        scope:this
                                }]
            
                        }]
                    },
                    {
                            xtype: 'panel',
                            region: 'center',
                            id: 'plotSection'
                    }]
            });
            
            Ext.plot.panel.superclass.initComponent.apply(this, arguments);
            Ext.getCmp('graphType').setValue('bar', true)
            Ext.getCmp('plotSampleSelect').setValue('sample_id')
            Ext.getCmp('graphType').on('change',this.display,this)
            this.on('afterlayout',function() {
                //console.log(Ext.get('plot_group_by'))
                if(Ext.get('plot_group_by') == undefined)
                    return;
                Ext.get('plot_group_by').on('click',
                    function(ee) {
                        if (Ext.getCmp('plot_group_by_Popout'))
                        { 
                            if(Ext.getCmp('plot_group_by_Popout').isVisible()) {
                                Ext.getCmp('plot_group_by_Popout').destroy()
                                //return;
                            }
                            else {
                                Ext.getCmp('plot_group_by_Popout').destroy()
                            }
                        }
                        this.plotTips = new Ext.Window({
                            title: "Plot Help",
                            id: 'plot_group_by_Popout',
                            ctCls: 'myPopup',
                            closable: true,
                            layout: 'anchor',
                            autoHeight: true,
                            autoWidth: true,
                            x: ee.xy[0],
                            y: ee.xy[1]-50,
                            stateful: false,
                            plain: true,
                            html: this.helpText.groupByTip
                        });
                        this.plotTips.show(this);
                    },
                this);

                
            },this)
    },
    display: function() { 
         if (sampleGrid.selected_tracks.length == 0) {
                 return;
         }

         var group = [];
        group = Ext.getCmp('plotSampleSelect').getValue().split(',')
        //console.log(group)
        
        var selections = Ext.getCmp('locationGrid').getSelectionModel().getSelections()
        //console.log(selections)
        if(Ext.getCmp('graphType').getValue().id =='line')
            this.plotLine(group,selections);
        else
            this.plotBar(group,selections);
    },
    plotBar: function(group,selections) {
        var series = [];
        var data = {};
        var n = {};
        var xaxis = [];
        for (var k = 0; k < selections.length; k++) {
            var l = locations[selections[k].json.location_id]
            for (var i = 0; i < sampleGrid.selected_tracks.length; i++) {

                x = sampleGrid.getStore().getAt(sampleGrid.getStore()
                .find('sample_id', sampleGrid.selected_tracks[i]))

                var label = [];
                for (var j = 0; j < group.length; j++) label.push(x.data[group[j]]);
                
                
                if (data[label.join('.')] == undefined) {
                    //order.push(label.join('.'))
                    data[label.join('.')] = {}
                    data[label.join('.')].name = label.join('.')
                    n[label.join('.')]= 1;
                } else {
                    n[label.join('.')]++;
                }
                if(data[label.join('.')][l.genename] == undefined) {
                    data[label.join('.')][l.genename] = x.data[l.location_id];
                } else {
                    data[label.join('.')][l.genename] += x.data[l.location_id]
                }
            }
        }
        //console.log(data)
        var xaxis = []
        for (var k = 0; k < selections.length; k++) {
            var l = locations[selections[k].json.location_id]
            xaxis.push({name:l.genename, label:l.genename,dataIndex:k,
                color:Ext.getCmp('locationGrid').getStore().indexOfId(selections[k].id)})
        }
        
        var order = []
        for (var k = 0; k < sampleGrid.getStore().getCount(); k++) {
            var label = []
            x = sampleGrid.getStore().getAt(k)
            for (var j = 0; j < group.length; j++) label.push(x.data[group[j]]);
            if(order.indexOf(label.join('.')) == -1)
                order.push(label.join('.'))
        }
        var finalData = []
        for (var k = 0; k < order.length; k++) {
            i = order[k]
            for(j in data[i]) {
                if(j == 'name' || j == undefined) continue;
                data[i][j] = data[i][j]/n[i]
            }
            if(data[i] != undefined)
                finalData.push(data[i]);
        }
        //console.log(xaxis)
         if (Ext.get('thePlot') != undefined)
         Ext.get('thePlot').remove();


         Ext.getCmp('plotSection').add({
                 xtype: 'barflot',
                 id: 'thePlot',
                 cls: 'x-panel-body',
                series: xaxis,
                data:finalData,
                
                 legend: false
         });
         Ext.getCmp('plotSection').doLayout();
         this.updateGrid();
    },
    plotLine: function(group,selections) {
        var series = [];
        
        var order = []
        for (var k = 0; k < sampleGrid.getStore().getCount(); k++) {
            var label = []
            x = sampleGrid.getStore().getAt(k)
            for (var j = 0; j < group.length; j++) label.push(x.data[group[j]]);
            if(order.indexOf(label.join('.')) == -1)
                order.push(label.join('.'))
        }
        
        for (var k = 0; k < selections.length; k++) {
            var l = locations[selections[k].json.location_id]
            var data = {};
            var n = {};
            var xaxis = [];

            for (var i = 0; i < sampleGrid.selected_tracks.length; i++) {
               x = sampleGrid.getStore().getAt(sampleGrid.getStore()
               .find('sample_id', sampleGrid.selected_tracks[i]))
               var label = [];
               for (var j = 0; j < group.length; j++) label.push(x.data[group[j]]);
               if (data[label.join('.')] == undefined) {
                    data[label.join('.')] = x.data[l.location_id];
                    n[label.join('.')] = 1;
               } else {
                    data[label.join('.')] += x.data[l.location_id]
                    n[label.join('.')]++;
               }
            }
            console.log(data)
            var finalData = [];
            
            var j = 0;
            for (var kk = 0; kk < order.length; kk++) {
                i = order[kk]
                // for (j in data) {
                if(data[i] == undefined) continue;
                finalData.push([j, data[i] / n[i]]);
                xaxis.push([j, i]);
                j++;
            }
            // }

            series.push({
                    label: l.genename,
                    data: finalData,
                    color:
                    Ext.getCmp('locationGrid').getStore().indexOfId(selections[k].id)
            });
        }
       //console.log(series)
        if (Ext.get('thePlot') != undefined)
        Ext.get('thePlot').remove();

        Ext.getCmp('plotSection').add({
                xtype: 'flot',
                id: 'thePlot',
                cls: 'x-panel-body',
                series: series,
                legend: false,
                lines: {
                        show: true
                },
                points: {
                        show: true
                },
                xaxis: {
                        ticks: xaxis
                }
        });
        Ext.getCmp('plotSection').doLayout();
        this.updateGrid();
    },
    updateGrid: function() {
            plotData = Ext.getCmp('thePlot').flot.getData()
            for (var i = 0; i < plotData.length; i++) {
                    var ind = Ext.getCmp('locationGrid').getStore().find('location', plotData[i].label)
                    Ext.get(Ext.getCmp('locationGrid').getView().getCell(ind, 1))
                    .applyStyles('background-color:' + plotData[i].color)
            }
    },
    cleanUp: function() {
    if(this.plotTips != undefined)
        this.plotTips.destroy()
    }


})


 Ext.plot.locationGrid = Ext.extend(Ext.grid.GridPanel, {
		id: 'locationGrid',
		stateful: false,
		initComponent: function() {

            this.ccolumns = [];
            var sm = new Ext.grid.CheckboxSelectionModel({
                    singleSelect: false,
                    checkOnly: true
            })
            this.ccolumns.push(sm)
            for (i = 0; i < config[current_genome].search.columns.length; i++) {
                    this.ccolumns.push(config[current_genome].search.columns[i])
            }
            this.ccolumns.push({
                    header: '<img src="images/cross.png" />',
                    width: 30,
                    sortable: false,
                    dataIndex: 'remove'
            });


            // console.log(this.ccolumns)
            var fields = []
            Ext.each(this.ccolumns,
            function(x) {
                fields.push({
                    mapping: x.dataIndex,
                    name: x.dataIndex
                })
            })
            this.fields = fields;

            //store = this.createStore();
            Ext.apply(this, {
                    store: new Ext.data.Store(),
                    id: 'locationGrid',
                    columns: this.ccolumns,
                    stripeRows: true,
                    title: '',
                    autoExpandColumn: 'location',
                    enableHdMenu: false,
                    enableDragDrop: false,
                    selModel: sm
            })
            Ext.plot.locationGrid.superclass.initComponent.apply(this, arguments);

            this.getSelectionModel().addListener({
                    selectionchange: {
                            fn: this.select_location,
                            buffer: 50,
                            scope: this
                    }

            })
            this.addListener({
                cellclick: {
                    fn: this.deleteLocation,
                    scope: this
                },
                afterrender: {
                    scope: this,
                    fn: function() {
                        this.addResults()
                    }
                }
            })
            
            this.getView().on({
            refresh:{scope:this,
                fn:function() {
                    this.getSelectionModel().selectAll();
                    //Ext.query('#locationGrid .x-grid3-col-checker');
                }
            }
            })
		},

		createStore: function() {
				var rows = [];
				for (i in locations) {
						var loc = locations[i];
						rows.push({
								location_id: loc.location_id,
								location: loc.genename,
								remove: '<img src="images/cross.png" />',
								plot: '<input type="checkbox" checked id="' + loc.genename + '">'
						})
				}
				var store = new Ext.data.Store({
						proxy: new Ext.data.MemoryProxy(rows),
						reader: new Ext.data.JsonReader({},
						this.fields)
				});
				store.load();
				return store;

		},
		addResults: function(update_location) {
				var store = this.createStore();
				this.reconfigure(this.createStore(),
				new Ext.grid.ColumnModel(this.ccolumns));
		},
		deleteLocation: function(g, rowIndex, columnIndex, e) {
				var record = g.getStore().getAt(rowIndex);
				if (columnIndex == 2) {
						this.getStore().remove(this.getStore().getAt(rowIndex))
						sampleGrid.removeColumn(record.json.location_id);
						delete locations[record.json.location_id];
						if (current_loc && current_loc.genename == record.json.location)
						current_loc = false;

						updateDisplay(true);
				}
		},
		select_location: function() {
				updateDisplay(true);
		}

})

